from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
import asyncio
from langChain.config import model
from langchain_community.chat_models import ChatTongyi

chain_1 = model | StrOutputParser()

# # 1.同步流式处理
# chunk = []
# for chunk in chain_1.stream(input="天空是什么颜色？"):
#     print(chunk,  end="--", flush=True)
# print('----------------------------------')


# # 2.异步流式处理
# async def task_1():
#     chunks = []
#     async for chunk in model.astream("天空是什么颜色？"):
#         chunks.append(chunk)
#         # 判断chunks长度为1的时候，打印chunks[0]
#         # if len(chunks) == 2:
#         #     print('--->',chunks[1])
#         print(chunk.content, end="--", flush=True)
#
#
# async def task_2():
#     chunks = []
#     async for chunk in model.astream("讲个笑话？"):
#         chunks.append(chunk)
#         # 判断chunks长度为1的时候，打印chunks[0]
#         # if len(chunks) == 2:
#         #     print('--->',chunks[1])
#         print(chunk.content, end="**", flush=True)
#
#
# async def main():
#     await asyncio.gather(task_1(), task_2())
#
#
# asyncio.run(main())
# # print('----------------------------------')

# # 3.使用JSON格式的输出解析器
# chain_2 = model | JsonOutputParser()
# result = chain_2.invoke("以JSON 格式输出法国、西班牙和日本的国家及其人口列表。"
#                 '使用一个带有“countries”外部键的字典，其中包含国家列表。'
#                 "每个国家都应该有键`name`和`population`"
#                 )
# print(f'JSON格式的输出解析器：{result}')
# print('----------------------------------')
